<template>
  <div class="major-rate-chart">
    <div class="major-chart-title">主营类型占比</div>
    <div class="major-chart-div">
      <div ref="chart"></div>
    </div>
  </div>
</template>

<script>
  export default {
    props: {
      majorRates: {
        type: Array,
        required: true
      }
    },

    data() {
      return {
        chart: null
      };
    },

    mounted() {
      this.initChart();
      this.resetChart();
      this.erd.listenTo(this.$el, this.chartResetSize);
    },

    methods: {
      initChart() {
        let chartDom = this.$refs['chart'];
        const chart = this.echarts.init(chartDom);
        let option = this.getOption();
        chart.setOption(option, true);
        this.chart = chart;
      },

      getOption() {
        return {
          legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 10,
            top: 20,
            bottom: 20
          },
          tooltip: {
            trigger: 'item',
            formatter: (param) => {
              let data = param.data;
              return `${param.marker} ${param.name} : ${data[1]} (${param.percent}%)`
            }
          },
          dataset: {
            source: []
          },
          series: [{
            type: 'pie'
          }]
        };
      },

      resetChart() {
        let majorRateList = this.majorRates;
        let majorRateArr = [];
        for (let i = 0; i < majorRateList.length; i++) {
          const majorRate = majorRateList[i];
          majorRateArr.push([majorRate.majorName, majorRate.majorCount]);
        }

        let chart = this.chart;
        chart.setOption({
          dataset: {
            source: majorRateArr
          }
        });
      },

      chartResetSize(){
        let chart = this.chart;
        if (chart !== null) {
          chart.resize();
        }
      }
    }
  };

</script>

<style lang="scss" scoped>
  .major-rate-chart {
    width: 100%;
    height: 100%;

    .major-chart-title {
      font-size: 20px;
      text-align: center;
    }

    .major-chart-div {
      height: calc(100% - 26px);

      >div {
        width: 100%;
        height: 100%;
      }
    }
  }

</style>
